package com.box.service.impl;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import com.box.entity.BlogSearch;
import com.box.entity.BlogTypeEntity;
import com.box.entity.DbBlog;
import com.box.entity.DbBlogExample;
import com.box.entity.DbBlogExample.Criteria;
import com.box.entity.DbBtype;
import com.box.entity.DbBtypeExample;
import com.box.entity.SelBlogAndType;
import com.box.mapper.DbBlogMapper;
import com.box.mapper.DbBtypeMapper;
import com.box.service.BlogService;
import com.box.service.lucene.BlogIndexService;
import com.box.utils.BaiduPage;
import com.box.utils.BaiduPageView;
import com.box.utils.Global;
import com.box.utils.LayuiResult;
import com.box.utils.MyUtil;
import com.box.utils.PageView;
import com.box.utils.PersonListPageView;
import com.box.utils.QueryResult;
import com.box.utils.SearchBaiduPage;
import com.box.utils.SearchGlobal;
import com.box.utils.SearchPageView;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.reflect.TypeToken;
import com.box.utils.Globals;
import com.box.utils.IDUtils;

@Service
public class BlogServiceImpl implements BlogService {
	
	@Autowired
	private DbBlogMapper BlogMapper;
	
	@Autowired
	private DbBtypeMapper btypeMapper;
	
	@Autowired // lucene搜索
	private BlogIndexService blogIndexService;
	
	//注入消息队列相关类
	@Autowired
	private JmsTemplate jmstemplate;
	
	//若有多线程启动，通过resource进行name
	@Resource(name="topicDestination")
	private Destination destination;


	public LayuiResult selBlogList(Integer page, Integer limit,
			BlogSearch search) {
		// TODO Auto-generated method stub
		try {
			//分页插件
			PageHelper.startPage(page, limit);
			//添加查询
			DbBlogExample example=new DbBlogExample();  
			example.setOrderByClause("leaseDaet desc");
			Criteria criteria = example.createCriteria();
			if(search.getTitle()!=null&&!search.getTitle().equals("")){
				criteria.andTitleLike("%"+search.getTitle()+"%");
				
			}
			if(search.getTypeid()!=null&&!search.getTypeid().equals("-1")){
				criteria.andTypeidEqualTo(Integer.parseInt(search.getTypeid()));
			}
			if(search.getKeyword()!=null&&!search.getKeyword().equals("")){
				criteria.andKeywordLike("%"+search.getKeyword()+"%");
			}
			if(search.getSummary()!=null&&!search.getSummary().equals("")){
				
				criteria.andSummaryLike("%"+search.getSummary()+"%");
				
			}
			if(search.getUppid()!=null&&!search.getUppid().equals("-1")){
				Integer uppid=Integer.parseInt(search.getUppid());
				criteria.andUppidEqualTo(uppid);
			}
			if(search.getCreateTimeStart()!=null&&!search.getCreateTimeStart().equals("")){
				criteria.andLeasedaetGreaterThanOrEqualTo(MyUtil.getDateByString(search.getCreateTimeStart()));
			}
			if(search.getCreateTimeEnd()!=null&&!search.getCreateTimeEnd().equals("")){
				
				criteria.andLeasedaetLessThanOrEqualTo(MyUtil.getDateByString(search.getCreateTimeEnd()));
			}
			List<DbBlog> list = BlogMapper.selectByExampleWithBLOBs(example);
			PageInfo<DbBlog> pageinfo=new PageInfo<DbBlog>(list);
			LayuiResult result=new LayuiResult();
			result.setCode(0);
			result.setMsg("获取博客列表成功");
			result.setCount(pageinfo.getTotal());
			result.setData(pageinfo.getList());
			
			return result;
		} catch (Exception e) {
			LayuiResult result=new LayuiResult();
			result.setCode(500);
			result.setMsg("获取博客列表失败");
			result.setCount(null);
			result.setData(e);
			
			return result;
		}
		
	}

	public Integer delBlogById(Integer id) {
		// TODO Auto-generated method stub
		Integer n=0;
		n =BlogMapper.deleteByPrimaryKey(id);
		try {


			n=2;
		blogIndexService.deleteIndexByBlog(String.valueOf(id));

			System.out.println("索引删除成功:"+n);
		return n;



		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
System.out.println("单条博客记录删除失败");
		}
		return n;
		
	}

	//封装消息队列发送机制
	private void sendMessage(final Integer blogId,Destination destination){
		jmstemplate.send(destination,new MessageCreator(){

			public Message createMessage(Session session) throws JMSException {
				// TODO Auto-generated method stub
				return session.createTextMessage(blogId+"");
			}
			
		});
		
	}
	public Integer delBlogByMany(String BlogStr) throws Exception {
		// TODO Auto-generated method stub
		String[] ids = BlogStr.split(",");
		Integer n=0;
		if(ids.length>0&&ids!=null){
			for (String id : ids) {
			n=	BlogMapper.deleteByPrimaryKey(Integer.parseInt(id));


			}
		}

		
		return n;
	}

	public BlogTypeEntity selBlogById(Integer id) {
		// TODO Auto-generated method stub
		DbBlog blognot = BlogMapper.selectByPrimaryKey(id);
		Integer clickhit = blognot.getClickhit();
		Integer n=++clickhit;

	DbBlog blog=new DbBlog();
	blog.setClickhit(n);
	blog.setId(id);
	int updateByPrimaryKeySelective = BlogMapper.updateByPrimaryKeySelective(blog);


	 BlogTypeEntity selBlogByOne = BlogMapper.selBlogByOne(id);
	return selBlogByOne;
	}

	public Integer InsertBlog(DbBlog blog) {
		// TODO Auto-generated method stub
		Integer n=0;
		blog.setLeasedaet(new Date());


	 n= BlogMapper.insert(blog);
		try {
			n=2;
			DbBlog zblog = BlogMapper.selectByPrimaryKey(blog.getId());
	//		blogIndexService.addIndexByBlog(blog);
			sendMessage(zblog.getId(), destination);
			return n;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.out.println("添加博客索引出问题");
		}
		return n;
	}

	public Integer UpdateBlog(DbBlog blog) {
		// TODO Auto-generated method stub
		blog.setLeasedaet(new Date());
	Integer n = 0;
	n=BlogMapper.updateByPrimaryKeySelective(blog);

		try {
			n=2;
	//	blogIndexService.updateIndexByBlog(blog);
		sendMessage(blog.getId(), destination);
		return n;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.out.println("修改博客失败");
		}
		return n;
	}

	public List<DbBlog> selBlogByType(Integer typeid) {
		// TODO Auto-generated method stub
		DbBlogExample example=new DbBlogExample();
		example.setOrderByClause("leaseDaet desc");
		Criteria criteria = example.createCriteria();
		criteria .andTypeidEqualTo(typeid);
		criteria.andUppidEqualTo(2);
		 
		return BlogMapper.selectByExampleWithBLOBs(example);
	}

	public List<DbBlog> selBlogList() {
		// TODO Auto-generated method stub
		DbBlogExample example=new DbBlogExample();
		example.setOrderByClause("leaseDaet desc");
		Criteria createCriteria = example.createCriteria();
		//前端只允许显示已审核过的博客
		createCriteria .andUppidEqualTo(2);
		List<DbBlog> list = BlogMapper.selectByExampleWithBLOBs(example);
		return list;
	}



	public List<DbBlog> selBlogListByClickHit() {
		// TODO Auto-generated method stub

	
	
		List<DbBlog> list = BlogMapper.selBlogListByClickHit();
	
		return list;
	}

	//个人博客日记列表
	public BaiduPage  selBlogByAjAx(Integer page) {
		// (page - 1) * Globals.PAGE_NUM, Globals.PAGE_NUM
		PageHelper.startPage(page,Globals.PAGE_NUM);
		
		DbBlogExample example=new DbBlogExample();
		example.setOrderByClause("leaseDaet desc");
		Criteria createCriteria = example.createCriteria();
		createCriteria .andTypeidEqualTo(1);
		createCriteria.andUppidEqualTo(2);
		List<DbBlog> selectByExample = BlogMapper.selectByExampleWithBLOBs(example);
		
	
		
		PageInfo<DbBlog> pageinfo=new PageInfo<DbBlog>(selectByExample);
		Long total = pageinfo.getTotal();

	
		
	PersonListPageView<DbBlog> pageView=new PersonListPageView<DbBlog>(page, total.intValue(), pageinfo.getList());
		Type listType = new TypeToken<PersonListPageView<DbBlog>>(){}.getType();
		BaiduPage result=new BaiduPage();
		result.setPageView(pageView);
		result.setListType(listType);
		
		return result;
	}

	public PageView searchBlogEntityByKeyWords(String keywords, String page) throws Exception {
		// TODO Auto-generated method stub
		
		int pageSize=3;
		if(StringUtils.isEmpty(page)){
			page="1";
		}

List<DbBlog> blogList = blogIndexService.searchBlog(keywords);
for (DbBlog dbBlog : blogList) {
	System.out.println(".................搜索出来的列表"+dbBlog);
}
Integer toIndex=blogList.size()>=Integer.parseInt(page)*pageSize?Integer.parseInt(page)*pageSize:blogList.size();
	


	

	BaiduPageView<DbBlog> pageView=new BaiduPageView<DbBlog>(Integer.parseInt(page), blogList.size(),blogList .subList((Integer.parseInt(page)-1)*pageSize, toIndex));
		Type listType = new TypeToken<BaiduPageView<DbBlog>>(){}.getType();
		
		PageView result=new PageView();
		result.setBaidu(pageView);
		result.setListType(listType);
		return result;
	}
	public SearchBaiduPage searchBlogByKeywods(String q, Integer page) {
		// TODO Auto-generated method stub
		PageHelper.startPage(page, SearchGlobal.PAGE_NUM);
		
		DbBlogExample example=new DbBlogExample();
		example.setOrderByClause("leaseDaet desc");
		Criteria createCriteria = example.createCriteria();
		createCriteria.andUppidEqualTo(2);
		if(!q.equals("")&&q!=null){
			createCriteria.andTitleLike(q);
			createCriteria.andSummaryLike(q);
			createCriteria.andKeywordLike(q);
		}
		
		
		List<DbBlog> blogList = BlogMapper.selectByExampleWithBLOBs(example);
		
		PageInfo<DbBlog> pageinfo=new PageInfo<DbBlog>(blogList);
		long total = pageinfo.getTotal();
		
		SearchPageView<DbBlog> pageView=new SearchPageView<DbBlog>(page, (int)total, pageinfo.getList());
		Type listType=new TypeToken<SearchPageView<DbBlog>>(){}.getType();
		SearchBaiduPage result=new SearchBaiduPage();
		result.setListType(listType);
		result.setSearchPageView(pageView);
		return result;
	}

	
	public List<DbBlog> selBlogListByReplyId() {
		// TODO Auto-generated method stub
		DbBlogExample example=new DbBlogExample();
		example.setOrderByClause("replyhit desc");
		Criteria createCriteria = example.createCriteria();
		createCriteria.andUppidEqualTo(2);
		List<DbBlog> list = BlogMapper.selectByExampleWithBLOBs(example);
		return  list;
	}

	public List<DbBlog> selBlogListByGuess() {
		// TODO Auto-generated method stub
		DbBlogExample example=new DbBlogExample();
		example.setOrderByClause("likeid desc");
		Criteria createCriteria = example.createCriteria();
		createCriteria.andUppidEqualTo(2);
		List<DbBlog> list = BlogMapper.selectByExampleWithBLOBs(example);
		return  list;
	}

	public BaiduPage selBlogByIndexAjax(Integer page) {
		// (page - 1) * Globals.PAGE_NUM, Globals.PAGE_NUM
				PageHelper.startPage(page,Global.PAGE_NUM);
				DbBlogExample example=new DbBlogExample();
				example.setOrderByClause("leaseDaet desc");		
				Criteria createCriteria = example.createCriteria();
				 createCriteria.andUppidEqualTo(2);
				List<DbBlog> selectByExample = BlogMapper.selectByExampleWithBLOBs(example);
				
		
				
				PageInfo<DbBlog> pageinfo=new PageInfo<DbBlog>(selectByExample);
				Long total = pageinfo.getTotal();
	
			
				
			PersonListPageView<DbBlog> pageView=new PersonListPageView<DbBlog>(page, total.intValue(), pageinfo.getList());
				Type listType = new TypeToken<PersonListPageView<DbBlog>>(){}.getType();
				BaiduPage result=new BaiduPage();
				result.setPageView(pageView);
				result.setListType(listType);
				
				return result;
	}

	public QueryResult<BlogTypeEntity> queryBlog(Integer firstIndex, Integer pageNum) {
		// TODO Auto-generated method stub
		QueryResult<BlogTypeEntity> query=new QueryResult<BlogTypeEntity>();
		List<BlogTypeEntity> list = BlogMapper.selBlogTypeALLTable(firstIndex, pageNum);
		
		Long count = BlogMapper.selCountByDbBlogAndType();
		query.setList(list);
		query.setTotalRecord(count);
		return query;
	}

	public PageView  selBlogListByIndexAjax(Integer page) {
		// TODO Auto-generated method stub
		QueryResult<BlogTypeEntity> query = queryBlog((page - 1) * Global.PAGE_NUM, Globals.PAGE_NUM);
		BaiduPageView<BlogTypeEntity> baidu=new BaiduPageView<BlogTypeEntity>(page, (int)query.getTotalRecord(), query.getList());
		Type listType = new TypeToken<BaiduPageView<BlogTypeEntity>>(){}.getType();

		PageView result = new PageView();
		result.setBaidu(baidu);
		result.setListType(listType);
		
		return result;
	}
/**
 * 
 * 	// TODO Auto-generated method stub
		DbBlog blognot = BlogMapper.selectByPrimaryKey(id);
		Integer clickhit = blognot.getClickhit();
		Integer n=++clickhit;
		System.out.println(n+"==后的结果");
	DbBlog blog=new DbBlog();
	blog.setClickhit(n);
	blog.setId(id);
	int updateByPrimaryKeySelective = BlogMapper.updateByPrimaryKeySelective(blog);
	System.out.println(updateByPrimaryKeySelective+"..增加浏览记录");
	DbBlogExample example=new DbBlogExample();
	Criteria createCriteria = example.createCriteria();
	createCriteria.andIdEqualTo(id);
	DbBlog blog2 = BlogMapper.selectByExampleWithBLOBs(example).get(0);
	return  blog2 ;
 * 
 * 
 */
	public Integer updateLikeId(Integer id) {
		// TODO Auto-generated method stub
		
		DbBlog bnot = BlogMapper.selectByPrimaryKey(id);
		Integer likeid = bnot .getLikeid();
			
		 Integer c=++likeid;
		
		 DbBlog b=new DbBlog();
		 b.setLikeid(c);
		 b.setId(id);
		int n = BlogMapper.updateByPrimaryKeySelective(b);
		return n;
	}

	public Integer selLikeIdById(Integer id) {
		// TODO Auto-generated method stub
		DbBlog b = BlogMapper.selectByPrimaryKey(id);
		return b.getLikeid();
	}

	public QueryResult<BlogTypeEntity> queryBlogByTypeId(Integer typeId, Integer firstIndex, Integer pageNum) {
		QueryResult<BlogTypeEntity> query=new QueryResult<BlogTypeEntity>();
		List<BlogTypeEntity> list = BlogMapper.selBlogTypeALLTableByBlog(typeId, firstIndex, pageNum);
		
		Long count = BlogMapper.selCountByDbBlogAndTypeByBlog(typeId);
		query.setList(list);
		query.setTotalRecord(count);
		return query;
	}

	public BaiduPage selBlogListByTypeId(Integer typeId,Integer page) {
		//QueryResult<BlogTypeEntity> query = queryBlog((page - 1) * Global.PAGE_NUM, Global.PAGE_NUM);
		QueryResult<BlogTypeEntity> query = queryBlogByTypeId(typeId, (page - 1) * Globals.PAGE_NUM, Globals.PAGE_NUM);
		PersonListPageView<BlogTypeEntity> baidu=new PersonListPageView<BlogTypeEntity>(page, (int)query.getTotalRecord(), query.getList());
		Type listType = new TypeToken<PersonListPageView<BlogTypeEntity>>(){}.getType();

		BaiduPage result = new BaiduPage();
		result.setPageView(baidu);
		result.setListType(listType);
		
		return result;
	}

	public LayuiResult selBlogByNotUppid(Integer page, Integer limit) {
		// TODO Auto-generated method stub
		try {
			PageHelper.startPage(page,limit);
			DbBlogExample example = new DbBlogExample();
			Criteria createCriteria = example.createCriteria();
			//获取未审核列表
			createCriteria.andUppidEqualTo(1);
			List<DbBlog> list = BlogMapper.selectByExampleWithBLOBs(example);
			PageInfo<DbBlog> pageinfo=new PageInfo<DbBlog>(list);
			LayuiResult result=new LayuiResult();
			result.setCode(0);
			result.setCount(pageinfo.getTotal());
			result.setMsg("获取未审核列表成功");
			result.setData(pageinfo.getList());
			return result;
		} catch (Exception e) {
			// TODO: handle exception
			LayuiResult result=new LayuiResult();
			result.setCode(500);
			result.setCount(null);
			result.setMsg("获取未审核列表失败");
			result.setData(e);
			return result;
		}
	
	}

	public LayuiResult selBlogByUppid(Integer page, Integer limit) {
		// TODO Auto-generated method stub
		try {
			PageHelper.startPage(page,limit);
			DbBlogExample example = new DbBlogExample();
			Criteria createCriteria = example.createCriteria();
			//获取未审核列表
			createCriteria.andUppidEqualTo(2);
			List<DbBlog> list = BlogMapper.selectByExampleWithBLOBs(example);
			PageInfo<DbBlog> pageinfo=new PageInfo<DbBlog>(list);
			LayuiResult result=new LayuiResult();
			result.setCode(0);
			result.setCount(pageinfo.getTotal());
			result.setMsg("获取已审核列表成功");
			result.setData(pageinfo.getList());
			return result;
		} catch (Exception e) {
			// TODO: handle exception
			LayuiResult result=new LayuiResult();
			result.setCode(500);
			result.setCount(null);
			result.setMsg("获取已审核列表失败");
			result.setData(e);
			return result;
		}
	}

	public Integer updateBlogStatusByUppid(Integer id) {
		// TODO Auto-generated method stub
		DbBlog blog = BlogMapper.selectByPrimaryKey(id);
		Integer n=0;
		if(blog!=null){
			blog.setUppid(2);
			blog.setId(id);
		n=	BlogMapper.updateByPrimaryKeySelective(blog);
		return n;
		}else{
			n=0;
			return n;
		}

	}

	public Integer updateBlogStatusByNotUppid(Integer id) {
		// TODO Auto-generated method stub
				DbBlog blog = BlogMapper.selectByPrimaryKey(id);
				Integer n=0;
				if(blog!=null){
					blog.setUppid(1);
					blog.setId(id);
				n=	BlogMapper.updateByPrimaryKeySelective(blog);
				return n;
				}else{
					n=0;
					return n;
				}
	}

	public Integer updateBlogByUppid(String BlogStr) {
		// TODO Auto-generated method stub
		String[] ids = BlogStr.split(",");
		Integer n=0;
		if(ids!=null&&ids.length>0){
			for (String id : ids) {
				DbBlog b = BlogMapper.selectByPrimaryKey(Integer.parseInt(id));
				b.setUppid(2);
				b.setId(Integer.parseInt(id));
		n=		BlogMapper.updateByPrimaryKeySelective(b);
		System.out.println("批量修改成功"+n);
			}
		}
		return n;
	}

	public Integer updateBlogByNotUppid(String BlogStr) {
		// TODO Auto-generated method stub
				String[] ids = BlogStr.split(",");
				Integer n=0;
				if(ids!=null&&ids.length>0){
					for (String id : ids) {
						DbBlog b = BlogMapper.selectByPrimaryKey(Integer.parseInt(id));
						b.setUppid(1);
						b.setId(Integer.parseInt(id));
				n=		BlogMapper.updateByPrimaryKeySelective(b);
				System.out.println("批量修改成功"+n);
					}
				}
				return n;

	}

	public SelBlogAndType selBlogTypeByTypeId(Integer typeId) {
		// TODO Auto-generated method stub
		
		//查询博客类型列表
		DbBtypeExample example = new DbBtypeExample();
		DbBtypeExample.Criteria createCriteria = example.createCriteria();
		createCriteria .andTidEqualTo(typeId);
		DbBtype dbBtype = btypeMapper.selectByExample(example).get(0);
		DbBlogExample exampleBlog=new DbBlogExample();
		Criteria createCriteria2 = exampleBlog.createCriteria();
		exampleBlog.setOrderByClause("leaseDaet desc");
		createCriteria2.andTypeidEqualTo(typeId);
		List<DbBlog> blog = BlogMapper.selectByExampleWithBLOBs(exampleBlog);
		SelBlogAndType twotable=new SelBlogAndType(dbBtype, blog);
		
		
		return twotable;
	}

	

	



}
